package cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 使用cas实现自旋锁
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/20 下午 12:10
 */
public class CasSpinLock {
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        System.out.println("--- try lock");
        do {

        } while (!atomicReference.compareAndSet(null, thread));
        System.out.println("--- lock successful");
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        System.out.println("--- try unlock");
        atomicReference.compareAndSet(thread, null);
        System.out.println("--- unlock successful");
    }



    public static void main(String[] args) {
        CasSpinLock spinLock = new CasSpinLock();
        new Thread(()->{
            spinLock.lock();
            System.out.println("excute A");
             try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLock.unlock();
        },"A").start();
          try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }
        new Thread(()->{
            spinLock.lock();
            System.out.println("excute B");
             try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            spinLock.unlock();
        },"B").start();
    }

}
